<?php

/*

Desktopd Colors
Copyright (C) 2015  Desktopd Developer(s)

This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as
published by the Free Software Foundation, either version 3 of the
License, or (at your option) any later version.

This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
GNU Affero General Public License for more details.

You should have received a copy of the GNU Affero General Public License
along with this program.  If not, see <http://www.gnu.org/licenses/>.

https://www.gnu.org/licenses/agpl.html

*/


namespace Desktopd\Colors;


class MatrixTransform {
    protected $matrix = array();
    
    public function __construct() {
        $matrix = func_get_args();
        $length = func_num_args();
        for ($i = 0; $i < $length; $i++) {
            if (!is_array($matrix[$i])) {
                throw new \InvalidArgumentException('Every argument must be an array');
            }
            
            $newsize = count($matrix[$i]);
            if (isset($size)) {
                if ($size !== $newsize) {
                    throw new \LengthException('Invalid matrix');
                }
            }
            
            $size = $newsize;
            $this->matrix[] = $matrix[$i];
        }
    }
    
    public function transform(array $vector) {
        $resultLength = count($this->matrix);
        $originalLength = count($vector);
        for ($i = 0; $i < $resultLength; $i++) {
            if ($originalLength !== ($expectedLength = count($this->matrix[$i]))) {
                throw new \LengthException("This matrix expects a vector of length $expectedLength, a vector of length $originalLength passed");
            }
            
            $value = 0;
            for ($j = 0; $j < $originalLength; $j++) {
                $value += $vector[$j] * $this->matrix[$i][$j];
            }
            $result[] = $value;
        }
        
        return $result;
    }
    
    public function __invoke(array $vector) {
        return $this->transform($vector);
    }
}


// vim: ts=4 et ai

